package 笔试.兆翔科技.航班预定统计;

import java.util.Arrays;

public class LeetCode1109 {
    public static int[] corpFlightBookings(int[][] bookings, int n) {
        int[] nums = new int[n + 1];
        for (int[] booking : bookings) {
            int left = booking[0];
            int right = booking[1];
            int seat = booking[2];
            //开始累计每个位置的预定数量
            for (int i = left; i <= right; i++) {
                nums[i] += seat;
            }
        }
        //最后需要将[0,10,55,45,25,25]->[10,55,45,25,25]
        int[] array = Arrays.stream(nums).skip(1).map(Integer::valueOf).toArray();
        return array;
    }

    public static int[] corpFlightBookings1(int[][] bookings, int n) {
        int[] nums = new int[n];
        for (int[] booking : bookings) {
            nums[booking[0] - 1] += booking[2];
            if (booking[1] < n) {
                nums[booking[1]] -= booking[2];
            }
        }
        for (int i = 1; i < n; i++) {
            nums[i] += nums[i - 1];
        }
        return nums;
    }

    public static int[] corpFlightBookings2(int[][] bookings, int n) {
        int[] nums = new int[n + 1];
        for (int[] booking : bookings) {
            int left = booking[0];
            int right = booking[1];
            int seat = booking[2];
            //差分
            nums[left] += seat;
            if (right < n) {    //如果不想要这个判断，差分数组大小需要为n+2才行
                nums[right + 1] -= seat;
            }
        }
        //对差分数组求前缀和
        for (int i = 1; i <= n; i++) {
            nums[i] += nums[i - 1];
        }
        return Arrays.stream(nums).skip(1).toArray();
    }

    public static void main(String[] args) {
        int[][] bookings = {
                {1, 2, 10},
                {2, 3, 20},
                {2, 5, 25}
        };
//        int[] res = corpFlightBookings(bookings, 5);
        int[] res = corpFlightBookings2(bookings, 5);
        System.out.println(Arrays.toString(res));
    }
}
